<template>
  <div class="printForm">
    <div class="area-header">
      <span class="area-header-title">{{ $t('申请单') }}</span>
    </div>
    <table class="printTable">
      <tr>
        <td class="tit">{{ $t('申请标题') }}</td>
        <td colspan="3">{{ form.actTitle }}</td>
      </tr>
      <tr>
        <td class="tit">{{ $t('申请人') }}</td>
        <td>
          <UserSelect
            v-model="form.applyUserId"
          />
        </td>

        <td class="tit">{{ $t('申请时间') }}</td>
        <td>{{ parseTime(form.applyTime) }}</td>
      </tr>
      <tr>
        <td class="tit">{{ $t('用印类型(一级)') }}</td>
        <td>
          {{ form.usineTypeOneName }}

        </td>

        <td v-if="form.source === '' || form.source === null || form.source === undefined" class="tit">{{ $t('用印类型(二级)') }}</td>
        <td v-if="form.source === '' || form.source === null || form.source === undefined">
          {{ form.usineTypeTwoName }}
        </td>
      </tr>
      <tr>
        <td class="tit">{{ $t('文件份数') }}</td>
        <td>{{ form.fileCount }}</td>
        <td class="tit">{{ $t('加盖骑缝章') }}</td>
        <td>{{ formatYesNo(form.sealRidingSeam) }}</td>
      </tr>
      <tr>
        <td class="tit">{{ $t('关联合同') }}</td>
        <td>
          {{ form.contractAssociatedName }}
        </td>
        <td class="tit">
          <span v-show="form.usineTypeOne !== 'other'" v-if="form.usineTypeOne === 'deal'">{{ $t('项目名称') }}</span>
          <span v-show="form.usineTypeOne !== 'other'" v-if="form.usineTypeOne === 'fund'">{{ $t('基金名称') }}</span>
        </td>
        <td>
          <MainBodySelect v-show="form.usineTypeOne !== 'other'" v-model="form.projectOrFund" :is-echo="true" :parameters="form.usineTypeOne" @change="schange" />
        </td>
      </tr>
      <tr>
        <td class="tit">{{ $t('备注') }}</td>
        <td colspan="3">{{ form.remark }}</td>
      </tr>
    </table>

    <!--用印明细-->
    <div v-if="form.oaSealDetailList && form.oaSealDetailList.length > 0">
      <div class="area-header">
        <span class="area-header-title">{{ $t('用印明细') }}</span>
      </div>
      <table class="previewTable">
        <thead>
          <th>{{ $t('用印主体类型') }}</th>
          <th>{{ $t('用印主体') }}</th>
          <th>{{ $t('印章类型') }}</th>
          <th>{{ $t('备注') }}</th>
        </thead>
        <tbody>
          <tr v-for="(v, ind) in form.oaSealDetailList" :key="ind">
            <td>
              <dictSelect
                v-model="v.investMainType"
                :is-echo="true"
                dictionary="main_body_type"
              />
            </td>
            <td>
              <MainBodySelect
                v-model="v.investMain"
                :is-echo="true"
                :parameters="v.investMainType"
              />
            </td>
            <td>
              {{ selectDictLabels(sealTypeDict, v.sealType) }}
            </td>
            <td>{{ v.remark }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!--文件-->
    <FileView :list.sync="form.fileList" :file-title="$t('用印附件信息')" data-type="oa_seal" :business-id="form.projectOrFund" :btn-show="!otherBtnHide" :is-show-user-info="false">
      <template #th-name-after>
        <th>
          {{ $t('主体及印章') }}
        </th>
        <th>
          {{ $t('份数') }}
        </th>
      </template>
      <template #td-name-after="scope">
        <template v-if="!isEmpty(scope.row.slotData)">
          <td>
            <span v-for="(item, index) in scope.row.slotData" :key="index">
              <span v-if="scope.row.id === item.dataId && item.model === 'investSealType'">
                {{ showSelectDictLabels(item.value) }}
              </span>
            </span>
          </td>
          <td>
            <span v-for="(item, index) in scope.row.slotData" :key="index">
              <span v-if="scope.row.id === item.dataId && item.model === 'copies'">
                {{ item.value }}
              </span>
            </span>
          </td>
        </template>
        <template v-else>
          <td />
          <td />
        </template>
      </template>
    </FileView>
    <fileView :file-title="$t('其他附件信息')" :list.sync="form.fileListOther" data-type="oa_seal" :business-id="form.projectOrFund" :btn-show="!otherBtnHide" :is-show-user-info="false" />
    <FileView v-if="form.actStatus === 'W'" file-title="归档附件信息" :list.sync="form.archivedFileList" data-type="oa_seal_archived" :business-id="form.projectOrFund" :btn-show="!otherBtnHide" />

  </div>
</template>

<script>
    import { saveOaSeal, getOaSeal, deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
    import { selectSealList } from '@/api/oa/contract/oaContract'
    import MainBodySelect from '@/components/MainBodySelect'

    export default {
        components: {
          MainBodySelect
        },
        data() {
            return {
                // 是否隐藏保存按钮
                btnHide: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                loading: false,
                // 表单参数
                form: {},
                // 表单校验
                title: undefined,
                rules: {
                  applyUserId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  usineTypeOne: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  usineTypeTwo: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 操作按钮默认不展示
                buttonShow: true,
                // 校验用印明细不能为空
                oaSealDetailListRules: {
                  investMainType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  investMain: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  sealType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                dataType: 'oa_seal',
                uploaderOpen: false,
                // 合同下拉
                selectDropDownContract: [],
                // 合同下拉,用印类型一级
                oaSealOneTypeDict: [],
                usineTypeOneOption: [],
                // 用印二级类型
                usineTypeTwoOption: [],
                sealTypeDict: undefined,
                contractMessage: this.$t('请选择付款类型后获取合同'),
                contractPageLoading: false,
                selectDropDownContractTempCount: 0,
                fileInvestIdOptions: []
            }
        },
        mounted() {
          this.$bus.$emit('async_done')
        },
        created() {
            this.getDicts('seal_type').then(response => {
              this.sealTypeDict = response.data
            })
            this.getDicts('seal_usine_type').then(response => {
              this.oaSealOneTypeDict = response.data
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.selectDropDownContractTempCount = 0
                this.contractMessage = this.$t('请选择付款类型后获取合同')
                if (data != null && data !== '' && data.id !== undefined) {
                    this.loading = true
                    getOaSeal(data.id).then(response => {
                        this.form = response.data
                        this.searchContractSelect(this.form.projectOrFund)
                        this.initSlotInvestTypeDict()
                        this.loading = false
                    })
                } else {
                    this.loading = false
                    this.searchContractSelect(null)
                    this.reset()
                }
            },
            searchContractSelect(dealId) {
              this.selectDropDownContract = []
              this.selectDropDownContractTemp = []
              if (typeof dealId === 'object') {
                dealId && dealId.forEach(item => {
                  selectSealList({ dealId: item }).then(response => {
                    response.data && response.data.forEach(d => {
                      this.selectDropDownContract.push(d)
                    })
                    if (this.selectDropDownContractTempCount <= 0) {
                      this.selectDropDownContractTemp = response.data
                      this.selectDropDownContractTempCount++
                    }
                  })
                })
              } else {
                selectSealList({ dealId: dealId }).then(response => {
                  this.selectDropDownContract = response.data
                  if (this.selectDropDownContractTempCount <= 0) {
                    this.selectDropDownContractTemp = response.data
                    this.selectDropDownContractTempCount++
                  }
                })
              }
            },
            schange(val, name) {
              console.log(name, val)
              this.form.contractAssociated = ''
              this.searchContractSelect(val)
            },
            // 初始化动态字段下拉
            initSlotInvestTypeDict() {
              this.form.oaSealDetailList && this.form.oaSealDetailList.forEach((item) => {
                item.sealType && item.sealType.forEach(type => {
                  var dictLabel = item.investMainName
                  // 如果dictLabel最后一个字符是中文)则去不加空格
                  if (dictLabel && dictLabel.charAt(dictLabel.length - 1) !== '）') {
                    dictLabel = dictLabel + ' '
                  }
                  this.fileInvestIdOptions.push({
                    dictValue: item.investMain + '_' + type,
                    dictLabel: dictLabel + '一 ' + this.translationDictSealType(type)
                  })
                })
              })
            },
            translationDictSealType(val) {
              var find = this.sealTypeDict.find(obj => obj.dictValue === val)
              if (find) {
                return find.dictLabel
              }
              return ''
            },
            showSelectDictLabels(val) {
              console.log(val)
              var value = []
              var result = []
              try {
                if (typeof val === 'object') {
                  value = val
                } else {
                  value = JSON.parse(val)
                }
              } catch (e) {
                console.log(e)
              }
              value.forEach(item => {
                var find = this.fileInvestIdOptions.find(obj => obj.dictValue === item)
                if (find) {
                  result.push(find.dictLabel)
                }
              })
              return result.join(',')
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                applyUserId: this.$store.state.user.userId,
                applyTime: new Date(),
                usineTypeOne: undefined,
                usineTypeTwo: undefined,
                contractAssociated: undefined,
                projectOrFund: undefined,
                sealType: undefined,
                source: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                fileList: [],
                delFlag: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              if (this.$parent.$parent.reset !== undefined) {
                this.$parent.$parent.reset()
              }
            },
            // 关闭form页面
            closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
              }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
              this.$refs['form'].validate(valid => {
                var temp = this.form.oaSealDetailList
                if (temp === null || temp === undefined || temp === '' || temp <= 0) {
                  this.msgError(this.$t('至少添加一条用印明细'))
                } else {
                  // 验证数据
                  if (valid) {
                    // 弹出遮罩层
                    this.loading = true
                    // 保存数据
                    saveOaSeal(this.form).then(response => {
                      if (response.code === 200) {
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                          this.form.id = response.data
                          // 启动流程
                          this.startProcess(response.data)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm()
                        }
                        resolve()
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject()
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    reject()
                  }
                }
              })
              })
            },
            // 启动流程
            startProcess: function(dataId) {
              this.loading = false
              // 启动流程时候传入的参数
              const processData = {}
              // 待办标题
              processData.title = this.form.actTitle
              // 业务表名
              processData.dataTable = 'oa_seal'
              // 业务ID
              processData.dataId = dataId
              // 业务表单地址
              processData.formPath = '@/views/oa/seal/oaSealForm'
              processData.viewPath = '@/views/oa/seal/oaSealView'
              // 菜单标识(根据菜单标识判断的走哪个流程)
              processData.menuKey = 'oa_seal'
              this.startProcessByMenu(processData, () => {
                this.form.actStatus = 'D'
                this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                this.closeForm()
              })
            },
            // 用印明细
            addPayment() {
              const row = {
                id: undefined,
                investMainType: '',
                investMain: '',
                sealType: '',
                remark: ''
              }
              if (!(this.form.oaSealDetailList instanceof Array)) {
                this.$set(this.form, 'oaSealDetailList', [])
              }
              this.$nextTick(() => {
                this.form.oaSealDetailList.push(row)
              })
            },
            // 删除用印明细
            delHandle(index, row) {
              // eslint-disable-next-line no-undef
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    return deleteOaSealDetail(id)
                  }).then(() => {
                  this.form.oaSealDetailList.splice(index, 1)
                  return this.msgSuccess(this.$t('删除成功'))
                })
                  .catch(function() {})
              } else {
                this.form.oaSealDetailList.splice(index, 1)
              }
            },
            // 添加附件
            uploader() {
              this.uploaderOpen = true
              this.title = '上传附件'
            },
            // 获取附件列表
            getData(fileList) {
              this.form.fileList = fileList
            },
            // 删除附件
            delAdjunct(index) {
              this.form.fileList.splice(index, 1)
            },
            //
            usineTypeOneChange(usineTypeOne) {
              this.getDicts('seal_usine_type_' + usineTypeOne).then(response => {
                this.usineTypeTwoOption = response.data
              })
              this.form.contractAssociated = ''
              // 基金或项目时 清空OA合同. 日常用印时恢复OA合同
              this.oaSealOneTypeDict.some(item => {
                if (item.dictValue === usineTypeOne) {
                  this.form.businessType = usineTypeOne
                  if (usineTypeOne === 'deal') {
                    this.selectDropDownContract = []
                    this.contractMessage = this.$t('请先选择项目,加载该项目下的合同')
                  } else {
                    this.contractMessage = this.$t('请选择合同')
                    this.selectDropDownContract = this.selectDropDownContractTemp
                  }
                  if (usineTypeOne === 'deal' || usineTypeOne === 'fund') {
                    this.rules.projectOrFund = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
                  } else {
                    this.rules.projectOrFund = []
                  }
                }
              })
            },
            formatYesNo(val) {
              if (val === 'Y') {
                return '是'
              } else {
                return '否'
              }
            },
            viewContractPage(id) {
              var proArr = this.selectDropDownContract
              if (proArr !== null && proArr !== undefined && proArr !== '') {
                proArr.forEach(item => {
                  if (id === item.id) {
                    if (item.actId === undefined) {
                      id = item.rows.actId
                    } else {
                      id = item.actId
                    }
                  }
                })
              }
              if (id !== null && id !== '' && id !== undefined) {
                console.log(id)
                this.contractPageLoading = true
                this.$nextTick(() => {
                  var proData = {}
                  proData.actId = id
                  this.$refs.processInfoForm.init(proData)
                })
              } else {
                this.msgError(this.$t('请先选择一个合同!'))
              }
            }

        }
    }
</script>
